<?php
/**
 * --------------------------------------------------
 * 功能描述：数据库类
 * 修改标识：
 * 修改描述：
 *---------------------------------------------------
 */

class Db
{
    private $dbtype = 'mysql';             //数据库类型
    private $dbhost = '';    //数据库地址
    private $dbname = '';          //数据库名字
    private $dbroot = 'root';              //数据库账号
    private $dbpawd = '';  //数据库密码
    private $dbpro = '3306';               //数据库端口
    private $table = '';                   //表名
    private $where = '';                   //条件
    private $pdo = '';                     //数据库句柄
    public static $db = '';                //数据库对象


    /**
     * 连接数据库
     * @param $config [数据库配置参数]
     * @return object [返回句柄对象]
     */
    public function connect($config = [])
    {

        if ($config) {
            $this->dbhost = $config['dbhost'];
            $this->dbname = $config['dbname'];
            $this->dbroot = $config['dbroot'];
            $this->dbpawd = $config['dbpawd'];
            $this->dbpro = $config['dbpro'];
        }
        $dsn = "$this->dbtype:host=$this->dbhost;dbname=$this->dbname";
        $PDO = new PDO($dsn, $this->dbroot, $this->dbpawd);
        $this->pdo = $PDO;

    }

    /**
     * 选择数据库表 并创建对象
     * @param $table [表名]
     * @return object 返回对象
     */
    public static function Table($table)
    {
        if (empty(self::$db)) {
            self::$db = new self();
        }

        self::$db->connect();
        self::$db->table = $table;

        return self::$db;
    }

    /**
     * 条件
     * @param $where [表名]
     * @return object 返回对象
     */
    public function where($where)
    {
        $this->where = $where;
        return $this;
    }

    /**
     * 条件
     * @return array 查询单条语句
     */
    public function find()
    {
        $SQL='SELECT * FROM '.$this->table.' where '.$this->where .' limit 1';
        return 'sql';
//        return $this->pdo->query($SQL)->fetchAll()[0];
    }

    /**
     * 修改操作
     * @return int 受影响的行数
     *
     */
    public function exec()
    {
        return $this->pdo->exec($this->where);
    }

    /**
     * @return array [返回结果数组]
     */
    public function select()
    {
        $SQL='SELECT * FROM '.$this->table.' where '.$this->where;
        return $this->pdo->query($SQL)->fetchAll();
    }
}